package com.itemp.wifidirectsend;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/***
 * WiFi Direct Client
 *
 * 客户端发送文件
 */
public class SendFileActivity extends BaseActivity implements DirectActionListener {
    private static final String TAG = "SendFileActivity";
    private boolean wifiP2pEnabled;
    private WifiP2pInfo wifiP2pInfo;
    private List<WifiP2pDevice> wifiP2pDeviceList;
    private DeviceAdapter deviceAdapter;
    private WifiP2pDevice mWifiP2pDevice;
    private WifiP2pManager mWifiP2pManager;
    private WifiP2pManager.Channel mChannel;
    private DirectBroadcastReceiver broadcastReceiver;
    private TextView tvDeviceState, tvConnectionStatus;
    private Button btnDisconnect, btnChooseFile, btnDirectDiscover;
    private ListView rvDeviceList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_file);
        initDevice();
        initView();
    }

    private void initView() {
        wifiP2pDeviceList = new ArrayList<WifiP2pDevice>();
    }

    private void initDevice() {
        mWifiP2pManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
        mChannel = mWifiP2pManager.initialize(this, getMainLooper(), this);
        broadcastReceiver = new DirectBroadcastReceiver(mWifiP2pManager, mChannel, this);
        registerReceiver(broadcastReceiver, DirectBroadcastReceiver.getIntentFilter());
    }

    @SuppressLint("MissingPermission")
    @Override
    protected void onStart() {
        super.onStart();
        //搜索周边设备，回调函数用于通知方法是否调用成功
        //搜索结束后，系统就会触发 WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION 广播，
        //此时就可以调用 requestPeers 方法获取设备列表信息，此处用 RecyclerView 展示列表，
        //在onPeersAvailable 方法刷新列表
        if (!wifiP2pEnabled) {
            Log.d(TAG,"打开WiFi");
        }
        showLoadingDialog("Searching for nearby devices");
        mWifiP2pManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
            @Override
            public void onSuccess() {
                Log.e(TAG, "Discovery onSuccess");
                dismissLoadingDialog();
            }

            @Override
            public void onFailure(int reasonCode) {
                Log.e(TAG, "Discovery onFailure");
                dismissLoadingDialog();
            }
        });
        deviceAdapter = new DeviceAdapter(this,wifiP2pDeviceList);
        //setdeviceAdapter
        deviceAdapter.setOnItemClickListener(position -> {
            WifiP2pDevice wifiP2pDevice = wifiP2pDeviceList.get(position);
            if (wifiP2pDevice != null) {
                connect(wifiP2pDevice);
            }
        });

    }

    @Override
    protected void onStop() {
        super.onStop();
    }


    @Override
    public void onChannelDisconnected() {
        Log.d(TAG, "onDisconnection");
        wifiP2pDeviceList.clear();
        deviceAdapter.notifyDataSetChanged();
        tvConnectionStatus.setText("");
        wifiP2pInfo = null;
    }

    @Override
    public void wifiP2pEnabled(boolean enabled) {
        wifiP2pEnabled = enabled;
    }

    @Override
    public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo) {
        dismissLoadingDialog();
        wifiP2pDeviceList.clear();
        deviceAdapter.notifyDataSetChanged();
        btnDisconnect.setEnabled(true);
        btnChooseFile.setEnabled(true);
        Log.e(TAG, "onConnectionInfoAvailable");
        Log.e(TAG, "onConnectionInfoAvailable groupFormed: " + wifiP2pInfo.groupFormed);
        Log.e(TAG, "onConnectionInfoAvailable isGroupOwner: " + wifiP2pInfo.isGroupOwner);
        Log.e(TAG, "onConnectionInfoAvailable getHostAddress: " + wifiP2pInfo.groupOwnerAddress.getHostAddress());
        StringBuilder stringBuilder = new StringBuilder();
        if (mWifiP2pDevice != null) {
            stringBuilder.append("Connected device：");
            stringBuilder.append(mWifiP2pDevice.deviceName);
            stringBuilder.append("\n");
            stringBuilder.append("Connected device IP：");
            stringBuilder.append(mWifiP2pDevice.deviceAddress);
        }
        stringBuilder.append("\n");
        stringBuilder.append("isGroupOwner?：");
        stringBuilder.append(wifiP2pInfo.isGroupOwner ? "GroupOwner" : "Not GroupOwner");
        stringBuilder.append("\n");
        stringBuilder.append("GroupOwner IP：");
        stringBuilder.append(wifiP2pInfo.groupOwnerAddress.getHostAddress());
        tvConnectionStatus.setText(stringBuilder);
        if (wifiP2pInfo.groupFormed && !wifiP2pInfo.isGroupOwner) {
            this.wifiP2pInfo = wifiP2pInfo;
            //服务器端和客户端已经通过 Wifi P2P 连接在了一起，
            // 客户端也获取到了服务器端的IP地址，在选取好待发送的文件后就可以主动发起对服务器端的连接请求了
            //选择文件
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(intent, 1);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                Uri uri = data.getData();
                if (uri != null) {
                    String path = getPath(this, uri);
                    if (path != null) {
                        File file = new File(path);
                        if (file.exists() && wifiP2pInfo != null) {
                            FileTransfer fileTransfer = new FileTransfer(file.getPath(), file.length());
                            Log.e(TAG, "待发送的文件：" + fileTransfer);
                            new WifiClientTask(this, fileTransfer).execute(wifiP2pInfo.groupOwnerAddress.getHostAddress());
                        }
                    }
                }
            }
        }
    }

    private String getPath(Context context, Uri uri) {
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{"_data"}, null, null, null);
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    @SuppressLint("Range")
                    String data = cursor.getString(cursor.getColumnIndex("_data"));
                    cursor.close();
                    return data;
                }
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }


    @Override
    public void onDisconnection() {
        Log.d(TAG, "onDisconnection");
        btnDisconnect.setEnabled(false);
        btnChooseFile.setEnabled(false);
        wifiP2pDeviceList.clear();
        deviceAdapter.notifyDataSetChanged();
        tvConnectionStatus.setText("");
        wifiP2pInfo = null;
    }

    @Override
    public void onSelfDeviceAvailable(WifiP2pDevice wifiP2pDevice) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("deviceName: " + wifiP2pDevice.deviceName);
        stringBuilder.append("\n");
        stringBuilder.append("deviceAddress: " + wifiP2pDevice.deviceAddress);
        stringBuilder.append("\n");
        stringBuilder.append(
                "status: " + wifiP2pDevice.status + " " + WifiP2pUtils.getDeviceStatus(
                        wifiP2pDevice.status
                )
        );
        tvDeviceState.setText(stringBuilder.toString());
    }

    @Override
    public void onPeersAvailable(Collection<WifiP2pDevice> wifiP2pDeviceList) {
        Log.e(TAG, "onPeersAvailable :" + wifiP2pDeviceList.size());
        this.wifiP2pDeviceList.clear();
        this.wifiP2pDeviceList.addAll(wifiP2pDeviceList);
        deviceAdapter.notifyDataSetChanged();
        loadingDialog.cancel();
    }

    @SuppressLint("MissingPermission")
    //通过点击事件选中群主（服务器端）设备，通过 connect 方法请求与之进行连接
    private void connect(WifiP2pDevice mWifiP2pDevice) {
        WifiP2pConfig config = new WifiP2pConfig();
        if (config.deviceAddress != null && mWifiP2pDevice != null) {
            config.deviceAddress = mWifiP2pDevice.deviceAddress;
            config.wps.setup = WpsInfo.PBC;
            showLoadingDialog("Connecting device:" + mWifiP2pDevice.deviceName);
            Log.d(TAG, "正在连接deviceName: " + mWifiP2pDevice.deviceName);
            mWifiP2pManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
                @Override
                public void onSuccess() {
                    Log.e(TAG, "connect onSuccess");
                }

                @Override
                public void onFailure(int reason) {
                    showToast("connect onFailure ,reason = " + reason);
                    dismissLoadingDialog();
                }
            });
        }
    }

    private void disconnect() {
        mWifiP2pManager.cancelConnect(mChannel, new WifiP2pManager.ActionListener() {
            @Override
            public void onSuccess() {
                Log.e(TAG, "disconnect onSuccess");
            }

            @Override
            public void onFailure(int i) {
                Log.e(TAG, "disconnect onSuccess");
                tvConnectionStatus.setText("");
                btnDisconnect.setEnabled(false);
                btnChooseFile.setEnabled(false);
            }
        });
        mWifiP2pManager.removeGroup(mChannel, null);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        disconnect();
        if (broadcastReceiver != null) {
            unregisterReceiver(broadcastReceiver);
        }
    }
}